package com.project;

import com.project.config.ServletConfig;
import com.project.servlet.AddServlet;
import com.project.servlet.TestServlet;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.servlet.Servlet;

public class MainTomcat {
    private static ApplicationContext springContext =
            new AnnotationConfigApplicationContext(ServletConfig.class);


    public MainTomcat() {
        Tomcat tomcat = new Tomcat();
        //设置启动端口
        tomcat.setPort(8088);
        //设置http引擎
        tomcat.getConnector();

        //定义上下文
        Context context = tomcat.addContext("", null);
        //注册servlet，第一个参数为上下文对象，第二个参数为servlet名称，第三个参数为servlet对象
        Wrapper w = tomcat.addServlet(context, "test",
                (Servlet) springContext.getBean("test"));
        //注册servlet访问路径
        w.addMapping("/tt");

        Wrapper w1 = tomcat.addServlet(context, "add", new AddServlet());
        w1.addMapping("/add");


        try {
            //启动tomcat
            tomcat.start();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        new MainTomcat();
    }
}
